<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 5/31/24
 * Time: 2:09 PM
 */

namespace app\common\command;

use app\common\model\media\Media;
use app\common\model\media\MediaCreative;
use app\common\model\media_account\MediaAccount;
use app\common\service\media\KsService;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\console\Command;

class PullKsCreative extends Command
{
    protected function configure()
    {
        $this->setName('pull_ks_creative')
            ->addOption('date', null, Option::VALUE_OPTIONAL, '拉取日期')
            ->setDescription('拉取快手创意');
    }


    /**
     * 拉取快手报表
     *
     * @param Input $input
     * @param Output $output
     * @return bool|int|null
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function execute(Input $input, Output $output)
    {
        // 获取需要拉取报表的媒体账户
        $accounts = MediaAccount::with('link')
            ->where([
                ['media_id', '=', Media::SOURCE_KS],
                ['status', '=', 1],
                ['promotion_link_id', '<>', 0]
            ])->select();

        if ($accounts->isEmpty()) {

            return false;
        }
        $output->writeln('开始拉取快手创意，共计：' . $accounts->count() . '条');

        // 拉取时间
        if ($input->hasOption('date')) {
            $pullDate = $input->getOption('date');
        } else {
            $pullDate = date('Y-m-d', time());
        }

        foreach ($accounts as $account) {
            $service = new KsService($account->media_auth_id);
            if (!$link = $account->link ?? []) {
                continue;
            }
            $result = $service->getCreative($account->auth_advertiser_id, $account->advertiser_id, $pullDate);
            foreach ($result as $item) {
                if (!$item) {
                    continue;
                }
                $mc = MediaCreative::where('advertiser_id', $account->advertiser_id)
                    ->where('media_id', Media::SOURCE_KS)
                    ->where('promotion_link_id', $link->id)
                    ->where('unit_id', $item['unit_id'])
                    ->where('count_date', $pullDate)
                    ->findOrEmpty();
                // 处理视频素材
                $photoIds = $item['photo_ids'] ?? [];
                $video    = $service->getVideo($account->auth_advertiser_id, $account->advertiser_id, $photoIds);

                // 处理广告组报告
                $unitReport = $service->getUnitReport(
                    $account->auth_advertiser_id, $account->advertiser_id, [$item['unit_id']], $pullDate
                );

                if ($mc->isEmpty()) {
                    $mc                    = new MediaCreative();
                    $mc->media_id          = Media::SOURCE_KS;
                    $mc->advertiser_id     = $account->advertiser_id;
                    $mc->promotion_link_id = $link->id;
                    $mc->unit_id           = $item['unit_id'];
                    $mc->count_date        = $pullDate;
                }

                $mc->captions           = $item['captions'];
                $mc->cover_image_urls   = $item['cover_image_urls'];
                $mc->view_status_reason = $item['view_status_reason'];
                $mc->package_name       = $item['package_name'];
                $mc->photo_ids          = implode(',', $photoIds);

                if ($unitReport) {
                    $mc->charge        = $unitReport['charge'];
                    $mc->show          = $unitReport['show'];
                    $mc->photo_click   = $unitReport['photo_click'];
                    $mc->play_3s_ratio = $unitReport['play_3s_ratio'];
                    $mc->block         = $unitReport['block'];
                    $mc->report        = $unitReport['report'];
                    $mc->negative      = $unitReport['negative'];
                }

                if ($video) {
                    $mc->video_urls = implode(',', $video);
                }
                $mc->save();
            }
        }

        $output->writeln('拉取快手媒体创意完成');
    }

}
